import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler
} from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { relative } from 'path'
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'
import { IRequest } from '@/common/interfaces'

@Injectable()
export class UploadInterceptor implements NestInterceptor {
  constructor(private configService: ConfigService) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<string> {
    const req = context.switchToHttp().getRequest<IRequest>()

    return next.handle().pipe(
      map((filePath: string) => {
        const staticPath = this.configService.get('static.path')
        const str = relative(staticPath, filePath).replace(/\\/g, '/')

        return req.headers.origin + '/' + str
      })
    )
  }
}
